<template>
  <div class="app-container">

    <div class="filter-container add1">
      <el-form style="">
        <el-form-item>
          <!-- 按钮级别的控制,使用hasPerm来判断是否应该有添加这个按钮 -->
          <el-button type="primary" icon="plus" @click="showCreate" v-if="hasPerm('committee:add')">添加
          </el-button>
          <!-- 下载模板 -->
          <el-button @click="exportExcel" type="primary" icon="plus" v-if="hasPerm('committee:add')">下载导入模板
          </el-button>
					<!-- 使用后端导入 -->
          <el-button type="primary" icon="plus" v-if="hasPerm('committee:add')" size="small">导入
            <input type="file" id = "btn" ref="clearFile" name = "file" @change="importf(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
          </el-button>
          <el-button @click="exportExcelOpertor" type="primary" icon="plus" v-if="hasPerm('committee:add')" >导出</el-button>
          <el-button type="danger" v-if="multipleSelectionFlag" @click="delSelect">
              批量删除
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="searchWord">
      <el-input v-model="search" 
        placeholder="请输入搜索内容" @input="inputFunction()">
      </el-input>
    </div>

    <br>
    <el-table class="tabless" :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit
              highlight-current-row :row-class-name="tableRowClassName" @selection-change="handleSelectionChange">
              <el-table-column
      type="selection"
      width="55">
    </el-table-column>
      <el-table-column align="center" label="序号" width="80">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)"> </span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="committee_name" label="委员会名称" style="width: 60px;"></el-table-column>
      <el-table-column align="center" prop="committee_desc" label="委员会描述" style="width: 170px;"></el-table-column>

      <el-table-column align="center" label="管理" width="300" v-if="hasPerm('committee:update')">
        <template slot-scope="scope">
          <el-button type="primary" icon="edit" @click="showUpdate(scope.$index)">修改</el-button>
          <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary" @click="handleDelete(scope.$index, scope.row)">成员</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 删除提示框 -->
    <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
        <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="delVisible = false">取 消</el-button>
            <el-button type="primary" @click="deleteRow" >确 定</el-button>
        </span>
    </el-dialog>

    <!-- 批量删除提示框 -->
    <el-dialog title="提示" :visible.sync="delVisibleByBatch" width="300px" center>
        <div class="del-dialog-cnt">删除不可恢复，是否确定批量删除？</div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="delVisibleByBatch = false">取 消</el-button>
            <el-button type="primary" @click="delAll" >确 定</el-button>
        </span>
    </el-dialog>
    
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="listQuery.pageNum" 
      :page-size="listQuery.pageRow"
      :total="totalCount"
      :page-sizes="[3, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      class="pagination">
    </el-pagination>

    
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form class="small-space" :model="tempCommittee" label-position="left" label-width="100px"
               style='width: 500px; margin-left:50px;'>
        <el-form-item label="委员会名称" v-if="dialogStatus=='create' | dialogStatus=='update'">
          <el-input type="text" v-model="tempCommittee.committee_name">
          </el-input>
        </el-form-item>

        <el-form-item label="委员会描述" v-if="dialogStatus=='create' | dialogStatus=='update'">
          <el-input type="textarea" v-model="tempCommittee.committee_desc">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="success" v-if="dialogStatus=='create'" @click="createCommittee">创 建</el-button>
        <el-button type="primary" v-if="dialogStatus=='update'" @click="updateCommittee">修 改</el-button>
        
      </div>
    </el-dialog>
  </div>
</template>
<script>

  import FileSaver from "file-saver";
  import XLSX from "xlsx";
  export default {
    data() {
      return {
        totalCount: 0, //分页组件--数据总条数
        list: [],//表格的数据
        listLoading: false,//数据加载等待动画
        listQuery: {
          pageNum: 1,//页码
          pageRow: 3,//每页条数
          name: ''
        },
        // 为textMap中的属性,指定标题头
        dialogStatus: 'create',
        dialogFormVisible: false,
        textMap: {
          update: '编辑',
          create: '创建',
        },
        tempCommittee: {
          committee_id: "",
          committee_name: "",
          committee_desc: ""
        },
        delVisible:false,//删除提示弹框的状态
        delVisibleByBatch:false,//批量删除提示弹框的状态
        msg:"",//记录每一条的信息，便于取id
        delarr:[],//存放删除的数据
        multipleSelection:[],//多选的数据
        // 搜索框中的内容
        search:'',
        // 排序的列名
        prop:'',
        // 排序的方式:包括asc,desc等
        order:'',
        // 记录导出得时候跳页的之前的页数
        temp_page:3,

        multipleSelectionFlag : true,
      } 
    },
    computed:{
    },
    created() {
      this.getList();
    },
    methods: {

      clearFile() {
        this.$refs.clearFile.value = ''; // 清空file文件
      },
      // 导入
      importf(obj) {
        let _this = this;
        let inputDOM = this.$refs.inputer;   // 通过DOM取文件数据
        this.file = event.currentTarget.files[0];  
        var rABS = false; //是否将文件读取为二进制字符串
        var f = this.file;
        var reader = new FileReader();
        //if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function(f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function(e) {
              var bytes = new Uint8Array(reader.result);
              var length = bytes.byteLength;
              for(var i = 0; i < length; i++) {
                  binary += String.fromCharCode(bytes[i]);
              }
              var XLSX = require('xlsx');
              if(rABS) {
                  wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                        type: 'base64'
                  });
              } else {
                  wb = XLSX.read(binary, {
                        type: 'binary'
                  });
              }
              // outdata就是你想要的东西 excel导入的数据
              outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); 
              // excel 数据再处理
              let arr = []
              outdata.map(v => {
                  let obj = {}
                  obj.committee_name = v.委员会名称
                  obj.committee_desc = v.委员会描述
                  obj.committee_id = ""
                  arr.push(obj)
                  _this.tempCommittee = obj
                  console.log(_this.tempCommittee)
                  _this.createCommittee()
              })
              _this.accountList = [...arr];
            }
            alert("上传完毕！")
            _this.clearFile()
            reader.readAsArrayBuffer(f);
        }
        if(rABS) {
              reader.readAsArrayBuffer(f);
        } else {
              reader.readAsBinaryString(f);
        }
      },

      // 导入结束
      exportExcelOpertor(){
        this.temp_page = this.listQuery.pageRow;
        this.handleSizeChange(this.totalCount)
        window.setTimeout(this.exportExcel,50);
        window.setTimeout(this.delayTime,200);
      },
      delayTime(){
        this.listQuery.pageRow = this.temp_page
        this.generalFun();
      },
      exportExcel () {
        // 设置当前日期
        let time = new Date();
        let year = time.getFullYear();
        let month = time.getMonth() + 1;
        let day = time.getDate();
        let name = year + "" + month + "" + day;
        this.$nextTick(function () {
            let wb = XLSX.utils.table_to_book(document.querySelector('.tabless'));
            /* get binary string as output */
            let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'});
            try {
                FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), name + ".xlsx")
            } catch (e) {
                if (typeof console !== 'undefined') console.log(e, wbout)
            }
            return wbout
          })
        },
                
      inputFunction(){
        this.generalFun();
      },
      //单行删除
      handleDelete(index, row) {
        this.idx = index;
        this.msg=row;//每一条数据的记录
        this.delarr.push(this.msg.PackingId);//把单行删除的每条数据的id添加进放删除数据的数组
        this.delVisible = true;
      },
      // 当批量删除的时候,如果要是没有选中,弹出提醒
      delWarnInfo() {
        this.$message('请选择您要删除的数据');
      },
      //批量删除
      delAll() {
        var lengths = this.multipleSelection.length;
        
        for (let i = 0; i < lengths; i++) {
          this.api({
            url: "/committee/deleteCommittee",
            method: "post",
            data: this.multipleSelection[i]
          }).then(() => {
            this.generalFun();
          }).catch(() => {
            this.$message.error("删除失败")
          })
        }
        this.delVisibleByBatch = false;//关闭删除提示模态框
      },
            
      // 确定删除
      deleteRow(){
          // 写自己的删除的对象
          let committee = this.list[this.idx];
          this.api({
            url: "/committee/deleteCommittee",
            method: "post",
            data: committee
          }).then(() => {
            this.generalFun();
          }).catch((error) => {
            console.log(error); 
            this.$message.error("删除失败")
          })
          this.delVisible = false;//关闭删除提示模态框
      },
      delSelect(){
        const length = this.multipleSelection.length;
        if(length == 0){
          this.delWarnInfo();
        }else{
          this.delVisibleByBatch = true;//显示删除弹框
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        console.log(this.multipleSelection);
      },
      tableRowClassName({row, rowIndex}) {
        if (rowIndex % 2 === 1) {
          return 'warning-row';
        } else if (rowIndex % 2 === 0) {
          // return 'success-row';
        }
        return '';
      },
      getList() {
        //查询列表
        if (!this.hasPerm('committee:list')) {
          return
        }
        this.listLoading = true;
        this.api({
          url: "/committee/listCommittee",
          method: "get",
          params: this.listQuery
        }).then(data => {
          console.log(data)
          this.listLoading = false;
          this.list = data.list;
          this.tables = data.list;
          this.totalCount = data.totalCount;
        })
      },

      getListBySearch(val) {
        // console.log("val:"+val);
        //查询列表
        if (!this.hasPerm('committee:list')) {
          return
        }
        this.listLoading = true;
        this.listQuery.value = val;
        // console.log(this.listQuery);
        this.api({
          url: "/committee/listCommitteeBySearch",
          method: "get",
          params: this.listQuery
        }).then(data => {
          // console.log(data)
          this.listLoading = false;
          this.list = data.list;
          this.totalCount = data.totalCount;
        })
      },
      handleSizeChange(val) {
        //改变每页数量
        // alert("handleSizeChange()")
        this.listQuery.pageRow = val
        this.generalFun();
        // this.handleFilter();
      },
      handleCurrentChange(val) {
        //改变页码
        this.listQuery.pageNum = val
        this.generalFun();
        
      },
      getIndex($index) {
        //表格序号
        return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
      },
      showCreate() {
        //显示新增对话框
        this.tempCommittee.committee_name = "";
        this.tempCommittee.committee_desc = "";
        this.dialogStatus = "create"
        this.dialogFormVisible = true
      },
      showUpdate($index) {
        //显示修改对话框
        //绑定相应的id
        this.tempCommittee.committee_id = this.list[$index].committee_id;
        //绑定相应的内容
        this.tempCommittee.committee_name = this.list[$index].committee_name;
        this.tempCommittee.committee_desc = this.list[$index].committee_desc;
        this.dialogStatus = "update"
        this.dialogFormVisible = true
      },
      createCommittee() {
        this.api({
          url: "/committee/addCommittee",
          method: "post",
          data: this.tempCommittee
        }).then(() => {
          this.getList();
          this.dialogFormVisible = false
        })
      },
      updateCommittee() {
        //修改文章
        this.api({
          url: "/committee/updateCommittee",
          method: "post",
          data: this.tempCommittee
        }).then(() => {
          this.getList();
          this.dialogFormVisible = false
        })
      },

      generalFun(){
        if(this.search){
          this.getListBySearch(this.search);
        }else{
            this.getList();
        }
      }
    }

}
</script>


<style>
.el-table .warning-row {
    background:whitesmoke;
    
     /* background: #ffffff; */
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  
  .pagination{
    background-color:lavender;
    margin-right: 0%;
    text-align: right;
  }

  .searchWord .add1{
    display: inline;
  }

  #btn{
            /* padding: 5px 10px;
            background: #00b0f0;
            color: #FFF;
            border: none;
            border-radius: 5px; */
        }


</style>